package com.yang.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.yang.util.JwtUtil;
import com.yang.util.ResponseKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;



@Component
public class LoginInterceptor implements HandlerInterceptor {

	private static final Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		System.out.println("登录拦截器");
		Map<String, Object> map = new HashMap<>();
		try {

			response.setHeader("Content-type", "application/json;charset=UTF-8");
			String token = request.getHeader("token");
			if (token != null) {
				boolean verify = JwtUtil.verify(token);
				if (verify) {
					return true;
				}
			}
			map.put(ResponseKey.MESSAGE, "token验证失败，请重新登录");
			map.put(ResponseKey.SUCCESS, false);
			map.put(ResponseKey.TOKEN_EXPIRE, true);
			response.getWriter().write(JSONObject.toJSONString(map));
			return false;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			map.put(ResponseKey.MESSAGE, "token验证失败，程序错误");
			map.put(ResponseKey.SUCCESS, false);
			map.put(ResponseKey.TOKEN_EXPIRE, true);
			response.getWriter().write(JSONObject.toJSONString(map));
			return false;
		}

	}

}
